<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ZY WiFi联网认证</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
        }
        
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background: linear-gradient(135deg, #6e8efb, #a777e3);
            padding: 20px;
        }
        
        .auth-container {
            width: 100%;
            max-width: 400px;
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            overflow: hidden;
        }
        
        .auth-header {
            background: #1976d2;
            color: white;
            padding: 25px 20px;
            text-align: center;
        }
        
        .auth-title {
            font-size: 22px;
            font-weight: 500;
            margin-bottom: 5px;
        }
        
        .auth-subtitle {
            font-size: 16px;
            opacity: 0.9;
        }
        
        .auth-body {
            padding: 25px 20px;
        }
        
        .notification {
            background: #e8f5e9;
            color: #2e7d32;
            padding: 12px 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
            display: none;
        }
        
        .success-notification {
            background: #e8f5e9;
            color: #2e7d32;
            padding: 20px 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 16px;
            display: none;
            text-align: center;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            display: block;
            font-size: 14px;
            color: #555;
            margin-bottom: 8px;
            font-weight: 500;
        }
        
        .form-input {
            width: 100%;
            padding: 14px 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        .form-input:focus {
            border-color: #1976d2;
            outline: none;
            box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.2);
        }
        
        .input-with-button {
            display: flex;
            gap: 10px;
        }
        
        .input-with-button .form-input {
            flex: 1;
        }
        
        .code-button {
            background: #f5f5f5;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 0 15px;
            font-size: 14px;
            color: #1976d2;
            cursor: pointer;
            white-space: nowrap;
            transition: all 0.3s;
        }
        
        .code-button:hover {
            background: #e8f1fd;
        }
        
        .code-button:disabled {
            background: #f5f5f5;
            color: #999;
            cursor: not-allowed;
        }
        
        .auth-actions {
            display: flex;
            gap: 15px;
            margin-top: 30px;
        }
        
        .auth-button {
            flex: 1;
            padding: 14px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .cancel-button {
            background: #f5f5f5;
            color: #666;
        }
        
        .cancel-button:hover {
            background: #e8e8e8;
        }
        
        .confirm-button {
            background: #1976d2;
            color: white;
            display: block !important;
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        .confirm-button.active {
            opacity: 1;
            cursor: pointer;
            background: #1976d2;
        }
        
        .confirm-button:hover {
            background: #1565c0;
        }
        
        .error-message {
            color: #d32f2f;
            font-size: 13px;
            margin-top: 5px;
            display: none;
        }
        
        .countdown-message {
            display: none;
            text-align: center;
            color: #1976d2;
            margin-top: 10px;
            font-size: 14px;
        }
        
        .close-button-container {
            display: none;
            text-align: center;
            margin-top: 20px;
        }
        
        .close-page-button {
            background: #4caf50;
            color: white;
            border: none;
            border-radius: 8px;
            padding: 12px 24px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .close-page-button:hover {
            background: #43a047;
        }
        
        .success-actions {
            display: flex;
            gap: 15px;
            justify-content: center;
            margin-top: 20px;
        }
        
        .success-button {
            padding: 12px 20px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .continue-button {
            background: #4caf50;
            color: white;
        }
        
        .continue-button:hover {
            background: #43a047;
        }
        
        @media (max-width: 480px) {
            .auth-container {
                border-radius: 12px;
            }
            
            .auth-header {
                padding: 20px 15px;
            }
            
            .auth-body {
                padding: 20px 15px;
            }
            
            .auth-actions {
                flex-direction: column;
                gap: 10px;
            }
            
            .success-actions {
                flex-direction: column;
                gap: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="auth-container">
        <div class="auth-header">
            <h1 class="auth-title">WiFi联网认证</h1>
            <p class="auth-subtitle">请输入手机号码完成认证</p>
        </div>
        
        <div class="auth-body">
            <div class="notification" id="codeSentMessage">
                验证码已发送，请查收
            </div>
            
            <div class="success-notification" id="successMessage">
                <div style="margin-bottom: 15px;">
                    <span style="font-size: 24px; margin-right: 10px;">✅</span>
                    <strong>认证成功！</strong>
                </div>
                <div id="countdownText">页面将在 <span id="countdown">3</span> 秒后关闭...</div>
            </div>
            
            <div class="form-group">
                <label class="form-label">手机号码</label>
                <input type="tel" id="phoneNumber" class="form-input" placeholder="请输入手机号" maxlength="11">
                <div class="error-message" id="phoneError"></div>
            </div>
            
            <div class="form-group">
                <label class="form-label">验证码</label>
                <div class="input-with-button">
                    <input type="text" id="verificationCode" class="form-input" placeholder="请输入6位验证码" maxlength="6" disabled>
                    <button type="button" class="code-button" id="getCodeButton" onclick="requestVerificationCode()">获取验证码</button>
                </div>
            </div>
            
            <div class="auth-actions">
                <button type="button" class="auth-button cancel-button" onclick="goBack()">取消</button>
                <button type="button" class="auth-button confirm-button" id="confirmButton" onclick="submitDeviceAuth()">确认</button>
            </div>
            
            <div class="countdown-message" id="countdownMessage">
                正在处理，请稍候...
            </div>
            
            <div class="close-button-container" id="closeButtonContainer">
                <div class="success-actions">
                    <button type="button" class="success-button continue-button" onclick="forceClosePage()">关闭页面</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量存储倒计时定时器
        var countdownTimer = null;
        var closePageTimer = null;
        var pageClosed = false;

        // 检测是否为移动设备
        function isMobileDevice() {
            return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        }

        // 强制关闭页面的方法
        function forceClosePage() {
            if (pageClosed) return;
            
            pageClosed = true;
            
            // 方法1: 尝试使用window.close()
            try {
                if (window.close && typeof window.close === 'function') {
                    window.close();
                }
            } catch (e) {
                console.log('window.close() 失败:', e);
            }
            
            // 方法2: 跳转到空白页
            setTimeout(function() {
                try {
                    window.location.href = 'about:blank';
                } catch (e) {
                    console.log('跳转到空白页失败:', e);
                }
            }, 100);
            
            // 方法3: 使用history.back()尝试返回
            setTimeout(function() {
                try {
                    window.history.back();
                } catch (e) {
                    console.log('history.back() 失败:', e);
                }
            }, 200);
            
            // 方法4: 替换当前页面为空白页
            setTimeout(function() {
                try {
                    window.location.replace('about:blank');
                } catch (e) {
                    console.log('location.replace 失败:', e);
                }
            }, 300);
            
            // 方法5: 对于iOS设备，尝试特殊处理
            if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
                setTimeout(function() {
                    try {
                        document.body.innerHTML = '<div style="text-align:center;padding:50px;font-size:18px;">认证已完成，请手动关闭页面</div>';
                    } catch (e) {
                        console.log('iOS特殊处理失败:', e);
                    }
                }, 400);
            }
            
            // 最终方法: 显示提示让用户手动关闭
            setTimeout(function() {
                if (!pageClosed) {
                    document.body.innerHTML = '<div style="text-align:center;padding:50px;font-size:18px;color:green;">✅ 认证已完成<br><br>请手动关闭此页面</div>';
                }
            }, 1000);
        }

        // 手机端友好的提示
        function showMobileAlert(message) {
            if (isMobileDevice()) {
                alert(message);
            } else {
                alert(message);
            }
        }

        // 验证手机号格式
        function validatePhoneNumber(phoneNumber) {
            var phoneRegex = /^1[3-9]\d{9}$/;
            return phoneRegex.test(phoneNumber);
        }

        // 显示手机号错误提示
        function showPhoneError(message) {
            var errorElement = document.getElementById('phoneError');
            var phoneInput = document.getElementById('phoneNumber');
            
            errorElement.textContent = message;
            errorElement.style.display = 'block';
            phoneInput.style.borderColor = '#d32f2f';
        }

        // 隐藏手机号错误提示
        function hidePhoneError() {
            var errorElement = document.getElementById('phoneError');
            var phoneInput = document.getElementById('phoneNumber');
            
            errorElement.style.display = 'none';
            phoneInput.style.borderColor = '#ddd';
        }

        // 显示验证码发送成功消息
        function showCodeSentMessage() {
            document.getElementById('codeSentMessage').style.display = 'block';
        }

        // 显示认证成功消息和倒计时
        function showSuccessMessage() {
            document.getElementById('successMessage').style.display = 'block';
            document.getElementById('codeSentMessage').style.display = 'none';
            
            // 隐藏表单
            document.querySelectorAll('.form-group, .auth-actions').forEach(el => {
                el.style.display = 'none';
            });
            
            // 显示关闭按钮
            document.getElementById('closeButtonContainer').style.display = 'block';
            
            // 在手机端额外显示alert提示
            showMobileAlert("认证成功！页面即将关闭");
            
            // 开始倒计时
            var countdown = 3;
            var countdownElement = document.getElementById('countdown');
            countdownElement.textContent = countdown;
            
            closePageTimer = setInterval(function() {
                countdown--;
                countdownElement.textContent = countdown;
                
                if (countdown <= 0) {
                    clearInterval(closePageTimer);
                    forceClosePage();
                }
            }, 1000);
        }

        // 显示处理中消息
        function showProcessingMessage() {
            document.getElementById('countdownMessage').style.display = 'block';
        }

        // 隐藏处理中消息
        function hideProcessingMessage() {
            document.getElementById('countdownMessage').style.display = 'none';
        }

        // 更新确认按钮状态
        function updateConfirmButtonState() {
            var confirmButton = document.getElementById('confirmButton');
            var verificationCode = document.getElementById('verificationCode').value;
            
            if (verificationCode.length === 6) {
                confirmButton.classList.add('active');
                confirmButton.disabled = false;
            } else {
                confirmButton.classList.remove('active');
                confirmButton.disabled = true;
            }
        }

        // 获取设备MAC地址
        function getDeviceMac() {
            return "00:1A:2B:3C:4D:5E";
        }

        // 发送XML请求到服务器
        function sendXMLRequest(xmlData, callback) {
            showProcessingMessage();
            
            try {
                var host = window.location.protocol + "//" + window.location.host + "/";
                var url = host + 'xml_action.cgi?method=set&module=duster&file=authentication';
                
                console.log('发送请求到:', url);
                
                var xhr = new XMLHttpRequest();
                xhr.open("POST", url, true);
                xhr.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");
                
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4) {
                        hideProcessingMessage();
                        console.log('响应状态:', xhr.status);
                        
                        if (xhr.status === 200) {
                            try {
                                if (xhr.responseXML) {
                                    var codeNode = xhr.responseXML.getElementsByTagName("code")[0];
                                    var msgNode = xhr.responseXML.getElementsByTagName("msg")[0];
                                    
                                    var code = codeNode ? codeNode.textContent : "";
                                    var msg = msgNode ? msgNode.textContent : "";
                                    
                                    if (msg && typeof UniDecode === 'function') {
                                        try {
                                            msg = UniDecode(msg);
                                        } catch (e) {
                                            console.warn('UniDecode失败:', e);
                                        }
                                    }
                                    
                                    console.log("响应代码:", code, "响应消息:", msg);
                                    
                                    if (typeof callback === 'function') {
                                        callback({
                                            success: code === "200",
                                            code: code,
                                            message: msg
                                        }, null);
                                    }
                                } else {
                                    console.error('无效的XML响应');
                                    callback(null, '无效的响应格式');
                                }
                            } catch (parseError) {
                                console.error('解析响应时出错:', parseError);
                                callback(null, '解析响应时出错');
                            }
                        } else {
                            console.error('请求失败，状态码:', xhr.status);
                            callback(null, '网络请求失败，状态码: ' + xhr.status);
                        }
                    }
                };
                
                xhr.onerror = function() {
                    hideProcessingMessage();
                    console.error('网络错误');
                    callback(null, '网络连接错误');
                };
                
                xhr.timeout = 15000;
                xhr.ontimeout = function() {
                    hideProcessingMessage();
                    console.error('请求超时');
                    callback(null, '请求超时');
                };
                
                xhr.send(xmlData);
                
            } catch (error) {
                hideProcessingMessage();
                console.error('发送请求时出错:', error);
                callback(null, '发送请求时出错: ' + error.message);
            }
        }

        // 请求验证码
        function requestVerificationCode() {
            var phoneNumber = document.getElementById('phoneNumber').value;
            var codeButton = document.getElementById('getCodeButton');

            hidePhoneError();

            if (!phoneNumber) {
                showPhoneError("请输入手机号");
                return;
            }
            
            if (!validatePhoneNumber(phoneNumber)) {
                showPhoneError("请输入有效的11位手机号码");
                return;
            }

            console.log("请求验证码，手机号: " + phoneNumber);
            
            // 禁用按钮并开始倒计时
            codeButton.disabled = true;
            var countdown = 60;
            
            if (countdownTimer) {
                clearInterval(countdownTimer);
                countdownTimer = null;
            }
            
            codeButton.textContent = '重新获取(' + countdown + 's)';
            
            countdownTimer = setInterval(function() {
                countdown--;
                if (countdown > 0) {
                    codeButton.textContent = '重新获取(' + countdown + 's)';
                } else {
                    clearInterval(countdownTimer);
                    countdownTimer = null;
                    codeButton.disabled = false;
                    codeButton.textContent = '获取验证码';
                }
            }, 1000);
            
            document.getElementById('verificationCode').disabled = false;
            document.getElementById('verificationCode').focus();
            
            var xmlRequest = 
                `<?xml version="1.0" encoding="US-ASCII"?>
                    <RGW>
                        <authentication>
                            <type>1</type>
                            <phone>${phoneNumber}</phone>
                            <mac>${getDeviceMac()}</mac>
                        </authentication>
                    </RGW>`;

            sendXMLRequest(xmlRequest, function(result, error) {
                if (error) {
                    showMobileAlert("验证码发送失败: " + error);
                    if (countdownTimer) {
                        clearInterval(countdownTimer);
                        countdownTimer = null;
                    }
                    codeButton.disabled = false;
                    codeButton.textContent = '获取验证码';
                    return;
                }

                if (result.success) {
                    showCodeSentMessage();
                    console.log("验证码发送成功:", result.message);
                    showMobileAlert("验证码已发送，请查收");
                } else {
                    showMobileAlert("验证码发送失败: " + (result.message || "未知错误"));
                    if (countdownTimer) {
                        clearInterval(countdownTimer);
                        countdownTimer = null;
                    }
                    codeButton.disabled = false;
                    codeButton.textContent = '获取验证码';
                }
            });
        }

        // 提交设备认证
        function submitDeviceAuth() {
            var phoneNumber = document.getElementById('phoneNumber').value;
            var verificationCode = document.getElementById('verificationCode').value;

            if (!verificationCode) {
                showMobileAlert("请输入验证码");
                return;
            }
            
            if (verificationCode.length !== 6) {
                showMobileAlert("验证码必须是6位数字");
                return;
            }

            console.log("提交认证，手机号: " + phoneNumber + ", 验证码: " + verificationCode);
            
            var confirmButton = document.getElementById('confirmButton');
            var originalText = confirmButton.textContent;
            confirmButton.textContent = '认证中...';
            confirmButton.disabled = true;
            
            var xmlAuthRequest = 
                `<?xml version="1.0" encoding="US-ASCII"?>
<RGW>
    <authentication>
        <type>2</type>
        <phone>${phoneNumber}</phone>
        <mac>${getDeviceMac()}</mac>
        <code>${verificationCode}</code>
    </authentication>
</RGW>`;

            sendXMLRequest(xmlAuthRequest, function(result, error) {
                confirmButton.textContent = originalText;
                confirmButton.disabled = false;
                updateConfirmButtonState();
                
                if (error) {
                    showMobileAlert("认证失败: " + error);
                    return;
                }

                if (result.success) {
                    showSuccessMessage();
                    console.log("认证成功:", result.message);
                } else {
                    showMobileAlert("认证失败: " + (result.message || "未知错误"));
                }
            });
        }

        // 重置表单
        function resetForm() {
            document.getElementById('phoneNumber').value = '';
            document.getElementById('verificationCode').value = '';
            document.getElementById('verificationCode').disabled = true;
            document.getElementById('codeSentMessage').style.display = 'none';
            document.getElementById('successMessage').style.display = 'none';
            document.getElementById('closeButtonContainer').style.display = 'none';
            
            document.querySelectorAll('.form-group, .auth-actions').forEach(el => {
                el.style.display = 'block';
            });
            
            if (countdownTimer) {
                clearInterval(countdownTimer);
                countdownTimer = null;
            }
            
            if (closePageTimer) {
                clearInterval(closePageTimer);
                closePageTimer = null;
            }
            
            document.getElementById('getCodeButton').disabled = false;
            document.getElementById('getCodeButton').textContent = '获取验证码';
            document.getElementById('confirmButton').classList.remove('active');
            document.getElementById('confirmButton').disabled = true;
            hidePhoneError();
        }

        // 返回登录页面
        function goBack() {
            if (confirm("确定要取消认证吗？")) {
                window.location.href = "index.html";
            }
        }

        // 初始化页面
        function initPage() {
            document.getElementById('confirmButton').disabled = true;
            document.getElementById('verificationCode').disabled = true;
            
            document.getElementById('phoneNumber').addEventListener('input', function() {
                if (this.value.length === 11) {
                    if (!validatePhoneNumber(this.value)) {
                        showPhoneError("手机号格式不正确");
                    } else {
                        hidePhoneError();
                    }
                } else if (this.value.length > 0) {
                    showPhoneError("手机号必须是11位数字");
                } else {
                    hidePhoneError();
                }
            });
            
            document.getElementById('verificationCode').addEventListener('input', function() {
                updateConfirmButtonState();
            });
            
            document.getElementById('verificationCode').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    if (document.getElementById('confirmButton').disabled === false) {
                        submitDeviceAuth();
                    }
                }
            });
        }

        window.onload = initPage;
    </script>
</body>
</html>